-- UIDungeonGoods
-- Create by luohj Jan/8/2015
-- 地牢商品详细信息界面

require "game/ui/base/TextColorM"

local SPELL_SHOP = "spell";

-- UIDungeonGoods继承自Layer
UIDungeonGoods = class("UIDungeonGoods", function()
    return cc.Layer:create();
end);

function UIDungeonGoods.create(pos, shopType, goodsIndex, goodsId)
    return UIDungeonGoods.new(pos, shopType, goodsIndex, goodsId);
end

-- 构造函数
function UIDungeonGoods:ctor(pos, shopType, goodsIndex, goodsId)
    self:setName("UIDungeonGoods");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/shop/GoodsDetail.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 2);

    -- 记录商品信息
    self.pos        = pos;
    self.shopType   = shopType;
    self.goodsId    = goodsId;
    self.goodsIndex = goodsIndex;

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 注册事件处理回调函数
function UIDungeonGoods:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIDungeonGoods界面析构清理");
            EventMgr.remove("UIDungeonGoods", event.BUY_DUNGEON_GOODS);
        end
    end);
end

-- 注册点击事件
function UIDungeonGoods:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIDungeonGoods");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确认购买按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/btn_buy");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 尝试购买
            self:tryBuy();
        end
    end
    btnBuy:addTouchEventListener(onBuyClick);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    if string.startWith(self.shopType, "showcase") then
        -- 解除封印
        btnBuy:setTitleText(getLocStr("unlock_seal"));
    else
        -- 确认购买
        btnBuy:setTitleText(getLocStr("confirm_to_buy"));
    end
end

-- 重绘
function UIDungeonGoods:redraw()
    -- 显示商品名称
    local CT = findChildByName(self.node, "CT");
    local nameLabel = CT:getChildByName("name");

    local goods = DungeonShopM.queryGoods(self.goodsId);
    local classId = goods[2];
    local goodNum = goods[3];
    local itemInfo = ItemM.query(classId);

    local nameDesc;
    if goodNum > 1 then
        nameDesc = string.format(getLocStr("item_bonus_format"), itemInfo["name"], goodNum);
    else
        nameDesc = itemInfo["name"];
    end

    if self.shopType == SPELL_SHOP then
        local rank = ItemM.query(classId, "rank") or 0;
        local rankText = FormulaM.invoke("GET_SPELL_RANK_NAME", rank);
        nameDesc = rankText .. nameDesc;
    end

    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
    nameLabel:setString(nameDesc);

    -- 显示商品价格
    local priceIconImg = CT:getChildByName("price_icon");
    local priceLabel   = CT:getChildByName("price");
    local price = DungeonShopM.queryPrice(self.goodsId);
    local payAttrib  = price[2];           -- 支付属性
    local priceAmount = price[3];          -- 商品价格

    -- 显示商品描述
    local desc = "";
    local detail = "";

    if SpellM.isSpell(classId) then
        -- 显示卷轴描述
        desc = ItemM.getItemDesc(classId);
        detail = ItemM.getItemDetail(classId, nil, "[blue]");
    else
        -- 显示普通物品描述
        desc = ItemM.getItemDesc(classId);
        detail = ItemM.getItemDetail(classId, nil, "[blue]");
    end

    local descLabel = CT:getChildByName("desc");

    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    descLabel:setString(desc);

    local detailLabel = CT:getChildByName("detail");

    TextStyleM.setTextStyle(detailLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);

    detailLabel = applyString(detailLabel, detail);

    -- 显示商品价格
    local price = DungeonShopM.queryPrice(self.goodsId);
    local payAttrib   = price[2];
    local priceAmount = price[3];
    local fieldName;
    local ownAmount;

    if type(payAttrib) == "number" then
        -- 道具
        fieldName = ItemM.query(payAttrib, "name");
        ownAmount = ItemM.getAmount(ME.user, payAttrib);
    else
        -- 属性
        fieldName = FieldsM.getFieldName(payAttrib);
        ownAmount = ME.user:queryAttrib(payAttrib);
    end

    local attribDesc = string.format(getLocStr("attrib_value_format"), ownAmount, priceAmount);
    if priceAmount > ownAmount then
        attribDesc = "[red]" .. attribDesc .. "[-]";
    end
    local costDesc = "";
    if string.startWith(self.shopType, "showcase") then
        costDesc = string.format(getLocStr("unlock_seal_cost2"), fieldName, attribDesc);
    else
        costDesc = string.format(getLocStr("buy_cost_attrib2"), fieldName, attribDesc);
    end

    costDesc = costDesc .. "\n";

    -- 显示拥有商品数量
    local amountLabel = CT:getChildByName("own_amount");

    TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GREEN);
    local amount = ItemM.getOwnedAmount(ME.user, classId);
    costDesc = costDesc .. string.format(getLocStr("own_goods_amount2"), amount);
    amountLabel = applyString(amountLabel, costDesc);

    -- 卷轴信息居中显示
    if SPELL_SHOP == self.shopType then
        self:setCenterAlign(detailLabel);
        self:setCenterAlign(nameLabel);
        self:setCenterAlign(amountLabel);
        self:setCenterAlign(descLabel);

        local bg1 = findChildByName(self.node, "CT/sub_bg_l");
        local bg2 = findChildByName(self.node, "CT/sub_bg_r");
        bg1:setVisible(true);
        bg2:setVisible(true);
    end

    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg");
    local btnBuy = findChildByName(self.node, "CT/btn_buy");
    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL,
        { nameLabel, descLabel, detailLabel, amountLabel, btnBuy});

    -- 适配角标
    AlignM.adaptSubBg(self.node);
end

-- 适配
function UIDungeonGoods:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 尝试购买
function UIDungeonGoods:tryBuy()
    -- 判断能否购买
    local ret = DungeonShopM.canBuyGoods(self.shopType .. self.pos, self.goodsIndex);
    if ret ~= true then
        AudioM.playFx("market_buy_failed");
        if ret == "sold_out" then
            -- 商品已售完
            alert(getLocStr("goods_sold_out"));
        elseif string.endWith(ret, "_lack") then
            -- 属性不足
            local field = string.sub(ret, 1, -6);
            local fieldName;

            if string.startWith(field, "item_") then
                local classId = tonumber(string.sub(field, 6, -1));
                fieldName = ItemM.query(classId, "name");
            else
                fieldName = FieldsM.getFieldName(field);
            end

            local msg = "";
            if string.startWith(self.shopType, "showcase") then
                msg = string.format(getLocStr("something_not_enough"), fieldName);
            else
                msg = string.format(getLocStr("fail_to_do_operate"), fieldName, getLocStr("buy"));
            end
            alert(msg);
        else
            -- 未知原因
            cclog("购买商品失败，原因：" .. ret );
        end
        -- 关闭当前界面
        UIMgr.getCurrentScene():removeFormByName("UIDungeonGoods");
        return;
    end

    -- 执行购买
    AudioM.playFx("market_buy_success");
    DungeonActionM.go("buy_goods", self.pos, self.goodsIndex);

    -- 关闭当前界面
    UIMgr.getCurrentScene():removeFormByName("UIDungeonGoods");
end

function UIDungeonGoods:setCenterAlign(textLabel)
    if textLabel == nil then
        return;
    end

    -- 设置锚点
    local yAnchor = textLabel:getAnchorPoint().y;
    textLabel:setAnchorPoint(cc.p(0.5, yAnchor));

    -- 设置位置
    textLabel:setPositionX(0);

    -- 设置文本居中
    textLabel:getVirtualRenderer():setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER);
end